<template>
	<view class="shop-buy">
		<swiper
			v-for="(buy, index) in buyProducts"
			:key="buy.id"
			class="buy-shop"
			:class="{ selected: buy.selected }"
			show-multiple-items="1"
			:right-width="180"
		>
			<swiper-item>
				<view class="shop-item-content">
					<image class="shop-img" :src="buy.url" @error="imageError($event, buy)" @click="toggleSelect(index)">
					</image>
					<view class="shop-item-info" @click="toggleSelect(index)">
						<text class="shop-item-name">{{ buy.name }}</text>
						<text class="shop-item-category">{{ buy.description }}</text>
						<text class="shop-item-price">¥{{ buy.price }}</text>
					</view>
					<view class="shop-item-quantity">
						<button class="shop-item-decrease" @click="decreaseQuantity(index)">-</button>
						<input class="shop-item-count" type="number" v-bind:value="buy.quantity"
							@input="updateQuantity(index, $event.target.value)" />
						<button class="shop-item-increase" @click="increaseQuantity(index)">+</button>
					</view>
				</view>
			</swiper-item>
			<swiper-item class="delete-item">
				<button class="shop-item-delete" @click="deleteBuyProduct(index)">删除</button>
			</swiper-item>
		</swiper>
	</view>
	<view class="shop-products">
		<view v-for="product in filteredProducts" :key="product.id" class="shop-product-card"
			@click="goToDetail(product, false)">
			<image :src="product.url" class="shop-product-image" mode="aspectFill"></image>
			<text class="shop-product-name">{{ product.商品名 }}</text>
			<text class="shop-product-price">¥{{ product.价格 }}</text>
		</view>
	</view>
	<view class="shop-check-out">
		<button @click="selectAll">全选/取消全选</button>
		<text>合计：￥{{ selectedTotal }}</text>
		<button @click="checkOut">结算</button>
	</view>
</template>

<style scoped>
	.shop-buy {
		display: flex;
		flex-direction: column;
		background-color: #fff;
		border-bottom: 1rpx solid #ddd;
		padding: 20rpx;
	}

	.buy-shop {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}

	.buy-shop.selected {
		border: 1px solid red;
	}

	.shop-item-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
	}

	.shop-item-info {
		display: flex;
		flex-direction: column;
		flex-basis: 50%;
		text-align: left;
		padding: 10rpx;
	}

	.shop-item-name {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin: 6rpx 0;
	}

	.shop-item-category {
		font-size: 24rpx;
		color: #666;
		margin: 6rpx 0;
	}

	.shop-item-price {
		font-size: 26rpx;
		color: #f14048;
		margin: 6rpx 0;
	}

	.shop-item-quantity {
		flex-basis: 30%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		min-width: 140rpx;
	}

	.shop-item-count {
		margin: 0 10rpx;
		font-size: 26rpx;
		color: #333;
		width: 75rpx;
		height: 40rpx;
		line-height: 40rpx;
		border-bottom: 1rpx solid #333;
		text-align: center;
	}

	.shop-img {
		width: 180rpx;
		height: 240rpx;
		object-fit: cover;
	}

	.delete-item {
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #ff4d4f;
	}

	.shop-item-delete {
		background-color: #ff4d4f;
		border: none;
		border-radius: 8rpx;
		color: white;
		font-size: 28rpx;
		padding: 10rpx 20rpx;
	}

	.shop-item-delete:hover {
		background-color: #ff7875;
	}

	.shop-item-decrease,
	.shop-item-increase {
		display: inline-block;
		width: 56rpx;
		height: 56rpx;
		line-height: 56rpx;
		border: 1rpx solid #ddd;
		border-radius: 50%;
		color: #333;
		text-align: center;
		font-size: 24rpx;
		font-weight: bold;
	}

	.shop-item-decrease:hover,
	.shop-item-increase:hover {
		border-color: #ff4d4f;
		background-color: #ff4d4fad;
		color: white;
	}

	.shop-products {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		width: 97%;
		background-color: #ffffff;
		padding: 0 10rpx;
	}

	.shop-product-card {
		width: 45%;
		margin: 8rpx 0;
		border: 2rpx solid #ddd;
		border-radius: 12rpx;
		padding: 8rpx;
		text-align: center;
		display: flex;
		flex-direction: column;
		align-items: center;
		overflow: hidden;
	}

	.shop-product-image {
		width: 100%;
		height: 250rpx;
		object-fit: cover;
	}

	.shop-product-name {
		margin: 10rpx 0;
		font-size: 28rpx;
		color: #333;
	}

	.shop-product-price {
		font-size: 32rpx;
		color: #f14048;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		max-width: 100%;
		display: block;
		box-sizing: border-box;
	}

	.shop-check-out {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: #ffffff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		box-sizing: border-box;
		z-index: 999;
	}

	.shop-check-out button {
		padding: 12rpx 20rpx;
		border: none;
		border-radius: 8rpx;
		background-color: #ff0000;
		color: white;
		font-size: 28rpx;
	}

	.shop-check-out text {
		font-size: 32rpx;
		font-weight: bold;
	}
</style>

<script>
export default {
	data() {
		return {
			posters: [],
			employees: [],
			categories: ['全部', '手机', '电脑', '食品', '男装', '生鲜', '家具厨具'],
			selectedCategory: '全部',
			defaultImage: '../../static/default.png', // 默认图片路径
			selectedProducts: [],
			buyProducts: [], // 存储从本地缓存中获取的产品数据
		};
	},
	created() {
		this.fetchEmployees();
		this.fetchPosters();
		this.loadBuyProducts(); // 加载本地缓存中的产品数据
	},
	onShow() {
		this.loadBuyProducts(); // 每次页面显示时刷新商品列表
	},
	computed: {
		filteredProducts() {
			return this.selectedCategory === '全部' ?
				this.employees :
				this.employees.filter(product => product.类型 === this.selectedCategory);
		},
		total() {
			return this.buyProducts.reduce((sum, item) => sum + item.price * item.quantity, 0).toFixed(2); // 保留两位小数
		},
		selectedTotal() {
			return this.buyProducts
				.filter(item => item.selected)
				.reduce((sum, item) => sum + item.price * item.quantity, 0)
				.toFixed(2);
		},
	},
	methods: {
		fetchEmployees() {
			uni.request({
				url: 'http://123.57.75.79:3000/employees',
				method: 'GET',
				success: (response) => {
					this.employees = response.data.map(product => ({
						...product,
						quantity: 1,
					}));
				},
				fail: (error) => {
					console.error('获取数据失败:', error);
				},
			});
		},
		fetchPosters() {
			uni.request({
				url: 'http://123.57.75.79:3000/customers',
				method: 'GET',
				success: (response) => {
					this.posters = response.data;
				},
				fail: (error) => {
					console.error('获取海报数据失败:', error);
				},
			});
		},
		loadBuyProducts() {
		  this.buyProducts = wx.getStorageSync('product') || [];
		  if (!Array.isArray(this.buyProducts)) {
		    this.buyProducts = []; // 确保buyProducts是一个数组
		  }
		},
		goToDetail(product, isBuy) {
			const url =
				`/pages/productdetail/productdetail?id=${product.id}&name=${encodeURIComponent(product.商品名)}&description=${encodeURIComponent(product.商品详情)}&price=${product.价格}&url=${encodeURIComponent(product.url)}`;
			if (isBuy) {
				wx.setStorageSync('selectedProduct', product);
			}
			wx.navigateTo({
				url
			});
		},
		imageError(event, product) {
			product.url = this.defaultImage;
		},
		addProductToCart(product) {
			let storedProducts = wx.getStorageSync('product') || [];
			const foundIndex = storedProducts.findIndex(item => item.id === product.id);

			if (foundIndex !== -1) {
				storedProducts[foundIndex].quantity += 1;
				this.$set(this.buyProducts, foundIndex, storedProducts[foundIndex]);
			} else {
				const newProduct = {
					...product,
					quantity: 1,
					selected: false,
				};
				storedProducts.push(newProduct);
				this.buyProducts.push(newProduct);
			}

			wx.setStorageSync('product', storedProducts);
		},
		deleteBuyProduct(index) {
			this.buyProducts.splice(index, 1);
			wx.setStorageSync('product', this.buyProducts);
		},
		updateQuantity(index, quantity) {
			const parsedQuantity = parseInt(quantity, 10);
			if (!isNaN(parsedQuantity) && parsedQuantity >= 1 && parsedQuantity <= 99) {
				this.$set(this.buyProducts[index], 'quantity', parsedQuantity);
			} else {
				this.$set(this.buyProducts[index], 'quantity', 1);
			}
			wx.setStorageSync('product', this.buyProducts);
		},
		increaseQuantity(index) {
			if (this.buyProducts[index].quantity < 99) {
				this.$set(this.buyProducts[index], 'quantity', this.buyProducts[index].quantity + 1);
				wx.setStorageSync('product', this.buyProducts);
			}
		},
		decreaseQuantity(index) {
			if (this.buyProducts[index].quantity > 1) {
				this.$set(this.buyProducts[index], 'quantity', this.buyProducts[index].quantity - 1);
				wx.setStorageSync('product', this.buyProducts);
			} else {
				this.deleteBuyProduct(index);
			}
		},
		selectAll() {
			const allSelected = this.buyProducts.every(item => item.selected);
			this.buyProducts.forEach(item => {
				item.selected = !allSelected;
			});
			wx.setStorageSync('product', this.buyProducts);
		},
		toggleSelect(index) {
			this.$set(this.buyProducts[index], 'selected', !this.buyProducts[index].selected);
			wx.setStorageSync('product', this.buyProducts);
		},
		 checkOut() {
		        wx.setStorageSync('buyProducts', this.buyProducts.filter(item => item.selected)); // 将已选中的商品存储到本地存储
		
		        // 清空当前页面的商品数组
		        this.buyProducts = [];
		        wx.setStorageSync('product', this.buyProducts);
		
		        wx.navigateTo({
		            url: `/pages/newsureorder/newsureorder?total=${this.selectedTotal}` // 传递 selectedTotal 参数
		        });
		    },
		refreshProducts() {
			this.buyProducts = wx.getStorageSync('product') || [];
			this.$forceUpdate();
		},
	},
	watch: {
		buyProducts: {
			handler() {
				this.$forceUpdate();
			},
			deep: true,
		},
	},
};
</script>
